import { setToken, setUser } from '@/utils/authority';
import { LoginForm, ProFormCaptcha, ProFormCheckbox, ProFormText } from '@ant-design/pro-form';
import { login } from './service';

import icon from '@/assets/icon.png';
import { useKeyPress } from '@umijs/hooks';
import { Col, Divider, message, Row, Tabs } from 'antd';
import React, { useState } from 'react';
import { history, useModel, useOutlet } from 'umi';
import styles from './index.less';

const Login = () => {
  const [submitting, setSubmitting] = useState(false);
  const [loginType, setLoginType] = useState('account');
  const { initialState, setInitialState } = useModel('@@initialState');

  const formRef = React.useRef();

  useKeyPress(['enter'], () => {
    formRef.current?.submit();
  });

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo();
    if (userInfo) {
      await setInitialState((s) => ({ ...s, currentUser: userInfo }));
    }
  };
  const fetchSignalRConnection = async (token) => {
    const connection = await initialState?.fetchSignalRConnection?.(token, '');
    if (connection) {
      await setInitialState((s) => ({ ...s, connectionHub: connection }));
    }
  };

  const handleSubmit = async (values) => {
    setSubmitting(true);
    try {
      // 登录
      const res = await login({ ...values });
      if (res.success) {
        const defaultLoginSuccessMessage = '登录成功！';
        message.success(defaultLoginSuccessMessage);
        // 保存到缓存中
        setUser(res.data);
        setToken(res.data.token);
        
        await fetchUserInfo(res.data);
        await fetchSignalRConnection(res.data.token);
        if (!history) {
          return;
        }

        setTimeout(() => {
          history.push('/');
        }, 100);
        return;
      } // 如果失败去设置用户错误信息

      message.error(res.message);

   
      // setUserLoginState(res);
    } catch (error) {
      // console.log(error)
      const defaultLoginFailureMessage = '登录失败，请重试！';
      message.error(defaultLoginFailureMessage);
    }

    setSubmitting(false);
  };

  const inputDefaultStyles = {
    borderBottom: '1px solid #e1e6eb',
    borderRadius: 0,
    // padding: '10px 0',
    margin: '0 6px',
  };

  const inputBlurAndFocus = {
    onBlur: (e) => {
      const op = e.target.parentElement;
      if (op) op.style.borderBottom = '1px solid #e1e6eb';
    },
    onFocus: (e) => {
      const op = e.target.parentElement;
      if (op) op.style.borderBottom = '1px solid #2D8CF0';
    },
  };

  // const { success } = userLoginState;
  const children = useOutlet();
  // 子页面
  if (children) {
    return children;
  }
  return (
    <div
      style={{ backgroundColor: '#bae0ff', minWidth: 1366, minHeight: 711 }}
      className={styles.outcontainer}
    >
      <div className={styles.container}>
        {/* <div className={styles.lang} data-lang>
          {SelectLang && <SelectLang />}
        </div> */}

        <div className={styles.contentw}>
          <div className={styles.content}>
            <div style={{ marginBottom: '20px' }}>
              <Row>
                <Col className={styles.logo} span={24}>
                  {' '}
                  <img src={icon} width="120px" />
                </Col>
                <Col span={24}>
                  {' '}
                  <span className={styles.logoTitle}> 用心运维(In)</span>
                </Col>
              </Row>
            </div>
            <Row>
              <Col flex="none">
                <Divider
                  type="vertical"
                  style={{ margin: 0, backgroundColor: '#F0F4F8', height: '89%', width: 1 }}
                />
              </Col>

              <Col flex="auto">
                <LoginForm
                  style={{ height: '350px' }}
                  actions={<></>}
                  submitter={{
                    searchConfig: {
                      submitText: '登录',
                    },
                    submitButtonProps: {
                      loading: submitting,
                      disabled: loginType === 'phone',
                      size: 'large',
                      style: {
                        width: '100%',
                        margin: '0 6px',
                        textAlign: 'center',
                        padding: '0',
                        transform: 'translateY(30px)',
                      },
                    },
                  }}
                  onFinish={async (values) => {
                    handleSubmit(values);
                  }}
                >
                  <Tabs
                    tabBarStyle={{ marginLeft: 6, marginRight: 6, width: 328 }}
                    size="large"
                    activeKey={loginType}
                    onChange={(activeKey) => setLoginType(activeKey)}
                    items={[
                      { key: 'account', label: '密码登录' },
                      // { key: 'phone', label: '手机号登录' },
                    ]}
                  />
      
                  {loginType === 'account' && (
                    <>
                      <ProFormText
                        name="username"
                        bordered
                        fieldProps={{
                          size: 'large',
                          bordered: false,
                          style: { ...inputDefaultStyles },
                          ...inputBlurAndFocus,
                          // prefix: <UserOutlined className={'prefixIcon'} />,
                        }}
                        placeholder={'输入账号'}
                        rules={[
                          {
                            required: true,
                            message: '请输入账号！!',
                          },
                        ]}
                      />
                      <ProFormText.Password
                        name="password"
                        fieldProps={{
                          size: 'large',
                          bordered: false,
                          style: { ...inputDefaultStyles },
                          ...inputBlurAndFocus,
                          // prefix: <LockOutlined className={'prefixIcon'} />,
                        }}
                        placeholder={'输入登录密码'}
                        rules={[
                          {
                            required: true,
                            message: '请输入密码！',
                          },
                        ]}
                      />
                    </>
                  )}
                  {loginType === 'phone' && (
                    <>
                      <ProFormText
                        fieldProps={{
                          size: 'large',
                          bordered: false,
                          style: { ...inputDefaultStyles },
                          ...inputBlurAndFocus,
                          // prefix: <MobileOutlined className={'prefixIcon'} />,
                        }}
                        name="mobile"
                        placeholder={'输入您的手机号'}
                        rules={[
                          {
                            required: true,
                            message: '请输入手机号！',
                          },
                          {
                            pattern: /^1\d{10}$/,
                            message: '手机号格式错误！',
                          },
                        ]}
                      />
                      <ProFormCaptcha
                        fieldProps={{
                          size: 'large',
                          bordered: false,
                          style: { ...inputDefaultStyles, width: '100%' },
                          ...inputBlurAndFocus,
                          // prefix: <LockOutlined className={'prefixIcon'} />,
                        }}
                        captchaProps={{
                          size: 'default',
                          style: {
                            border: 'none',
                            borderLeft: '1px solid #e1e6eb',
                            padding: '0 12px',
                            height: 20,
                            lineHeight: '20px',
                          },
                        }}
                        placeholder={'输入手机验证码'}
                        captchaTextRender={(timing, count) => {
                          if (timing) {
                            return `${count} ${'获取验证码'}`;
                          }
                          return '获取验证码';
                        }}
                        name="captcha"
                        rules={[
                          {
                            required: true,
                            message: '请输入验证码！',
                          },
                        ]}
                        onGetCaptcha={async () => {
                          message.success('获取验证码成功！验证码为：1234');
                        }}
                      />
                    </>
                  )}
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      margin: '30px 6px 0',
                      width: 328,
                      // marginBlockEnd: 54,
                    }}
                  >
                    <ProFormCheckbox noStyle name="autoLogin">
                      <span className={styles.ah}>自动登录</span>
                    </ProFormCheckbox>
                    <a className={styles.ah} onClick={() => { }}>
                      忘记密码
                    </a>
                  </div>
                </LoginForm>
              </Col>
            </Row>
            {/* <div className={styles.bbg} /> */}
            {/* <div className={styles.trangle} />
            <div className={styles.register} onClick={() => { }}>
              注册
            </div> */}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
